<?php
/**
 * 奖品类文件
 * 作者：刘单风
 * 最后修改时间：2018-11-24
 * 版权：医库PHP小组
 */

namespace app\model;
use app\model\modelbase\IBasemodel;
use think\Model;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Luckprizes extends Model implements IBasemodel
{
    function Luckprizes()
    {
        return [
            'id' => 0,
            'prize_title' => "",
            'prize_img' => "",
            'create_time' => "",
            'open_time' => "",
            'publish_time' => date('Y-m-d H:i'),
            'full_num' => 0,
            'sponsor_id' => 0,
            'prize_num' => 0,
            'prize_msg' => "",
            'sort_num' => 0,
            'prize_type' => 0,
            'user_id' => 0,
            'img_urls' => [],
            'imgurls' => "",
            'is_open' => 0
        ];
    }

    function dataList($where = [], $keywords = "",$opertype=0)
    {
        $where['is_logicdel'] = 0;
        $spids = [];
        $userids = [];
        if ($keywords) {
            $keywhere[] = ['prize_title', 'like', '%' . $keywords . '%'];
            //符合条件的赞助商
            $spids = Db::table('luck_sponsors')
                ->field('id')
                ->where('sp_name', 'like', "%$keywords%")
                ->column('id');
            $spids = $spids ?: -1;
            //查询符合条件的个人发起
            $userids = Db::table('luck_users')
                ->field('id')
                ->where('nick_name', 'like', "%$keywords%")
                ->column('id');
            $userids = $userids ?: -1;
        }
        if (empty($opertype)) {
            $data = Db::table('luck_prizes')
                ->where($where)
                ->where(function ($query) use ($spids, $userids, $keywords) {
                    $query->where('prize_title', 'like', "%$keywords%")
                        ->whereOr('sponsor_id', 'in', $spids)
                        ->whereOr('user_id', 'in', $userids);
                })
                ->order('id desc')
                ->paginate(20, false, ['query' => request()->param()])->each(function ($item, $key) {
                    if ($item['sponsor_id']) {
                        //获取赞助商名称
                        $sponsorModel = new Lucksponsor();
                        $sponsor = $sponsorModel->oneDetail(['id' => $item['sponsor_id']]);
                        $item['sp_name'] = $sponsor['sp_name'];
                    } else {
                        //个人发起
                        $user = Db::table('luck_users')
                            ->where('id', $item['user_id'])
                            ->find();
                        $item['sp_name'] = urldecode($user['nick_name']);
                    }

                    return $item;
                });
        } else {
            //导出数据,不分页了
            $data = Db::table('luck_prizes')
                ->where($where)
                ->where(function ($query) use ($spids, $userids, $keywords) {
                    $query->where('prize_title', 'like', "%$keywords%")
                        ->whereOr('sponsor_id', 'in', $spids)
                        ->whereOr('user_id', 'in', $userids);
                })
                ->order('id desc')
                ->select();
            for ($i = 0; $i < count($data); $i++) {
                $data[$i]['create_time'] = date("Y-m-d H:i", $data[$i]['create_time']);
                $data[$i]['open_time'] = $data[$i]['open_time'] ? (date("Y-m-d H:i", $data[$i]['open_time'])) : 0;
                $data[$i]['full_num'] = $data[$i]['full_num'] ? '按人数开奖' : '按时间开奖';
                $data[$i]['prize_type'] = $data[$i]['prize_type'] == 0 ? '单人' : '组团';
                $data[$i]['is_open'] = $data[$i]['is_open'] == 0 ? '未开奖' : '已开奖';
                //获取参与人数
                $join_num = Db::table('luck_join')
                    ->where('prize_id', $data[$i]['id'])
                    ->count();
                $data[$i]['join_num'] = $join_num;
                if ($data[$i]['sponsor_id']) {
                    //获取赞助商名称
                    $sponsorModel = new Lucksponsor();
                    $sponsor = $sponsorModel->oneDetail(['id' => $data[$i]['sponsor_id']]);
                    $data[$i]['sp_name'] = $sponsor['sp_name'];
                } else {
                    //个人发起
                    $user = Db::table('luck_users')
                        ->where('id', $data[$i]['user_id'])
                        ->find();
                    $data[$i]['sp_name'] = urldecode($user['nick_name']);
                }
            }
        }

        return $data;
    }

    function addOne($data)
    {
        $id = Db::table('luck_prizes')
            ->insertGetId($data);
        return $id;
    }

    function updateOne($data, $where)
    {
        Db::table('luck_prizes')
            ->where($where)
            ->update($data);
    }

    function oneDetail($where)
    {
        $data = Db::table('luck_prizes')
            ->where($where)
            ->find();
        if ($data) {
            $data['open_time'] = date('Y-m-d H:i',$data['open_time']);
            $data['publish_time'] = date('Y-m-d H:i',$data['publish_time']);
        }
        return $data;
    }

    function deleteOne($where)
    {
        // TODO: Implement deleteOne() method.
    }

    //中奖者列表
    function winnerlist($id)
    {
        $winners = Db::table('luck_join')
            ->field('user_id,addr_id')
            ->where('prize_id', $id)
            ->where('is_win', 'in', [1, 2])
            ->select();
        $prizetitle = Db::table('luck_prizes')
            ->field('open_time,prize_title,prize_type')
            ->where('id', $id)
            ->find();
        for ($i = 0; $i < count($winners); $i++) {
            $nickname = Db::table('luck_users')
                ->field('nick_name')
                ->where('id', $winners[$i]['user_id'])
                ->value('nick_name');
            $winners[$i]['nick_name'] = urldecode($nickname);
            $addr = Db::table('luck_address')
                ->where('id', $winners[$i]['addr_id'])
                ->find();
            $winners[$i]['addr'] = $addr;
            //过期了
            $winners[$i]['is_overdue'] = 0;
            //查看当前用户是否是过期没领
            if (empty($addr)) {
                //用户没领奖,查看是否过期
                $deadline = strtotime("+3 days", $prizetitle['open_time']);
                if (time() > $deadline) {
                    //过期了
                    $winners[$i]['is_overdue'] = 1;
                }
            }
            //查看当前用户邀请了多少人
            $visitcount = Db::table('luck_index')
                ->field('SUM(index_num) AS index_num')
                ->where('prize_id', $id)
                ->where('user_id', $winners[$i]['user_id'])
                ->group('user_id')
                ->order('index_num desc')
                ->find();
            $winners[$i]['visit_count'] = $visitcount['index_num'];
        }

        return ['winners' => $winners, 'prizetitle' => $prizetitle['prize_title'], 'prizetype' => $prizetitle['prize_type']];
    }
    /**
     * 导出excel表
     * $data：要导出excel表的数据，接受一个二维数组
     * $name：excel表的表名
     * $head：excel表的表头，接受一个一维数组
     * $key：$data中对应表头的键的数组，接受一个一维数组
     * 备注：此函数缺点是，表头（对应列数）不能超过26；
     *循环不够灵活，一个单元格中不方便存放两个数据库字段的值
     */
    public function dataexport($name='测试表', $data=[], $head=[], $keys=[])
    {
        $count = count($head);  //计算表头数量
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始，循环设置表头：
            $sheet->setCellValue(strtoupper(chr($i)) . '1', $head[$i - 65]);
        }

        /*--------------开始从数据库提取信息插入Excel表中------------------*/

        foreach ($data as $key => $item) {             //循环设置单元格：
            //$key+2,因为第一行是表头，所以写到表格时   从第二行开始写

            for ($i = 65; $i < $count + 65; $i++) {     //数字转字母从65开始：
                $sheet->setCellValue(strtoupper(chr($i)) . ($key + 2), $item[$keys[$i - 65]]);
                $spreadsheet->getActiveSheet()->getColumnDimension(strtoupper(chr($i)))->setWidth(20); //固定列宽
            }
        }
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');

        //删除清空：
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
        exit;
    }
}